//
// Created by linfe on 2023/4/2.
//
/**
* @file catlog_port.c in catlog
* @author linfe
* @comment
* Create on 2023/3/16 22:57
* @version 1.0
**/
#include "catlog_conf.h"
#include "catlog_port.h"
#include <stdio.h>
#include "catlog.h"
#include "bsp_board.h"




#define CATLOG_WEAK_DECLARE

CATLOG_WEAK_DECLARE uint32_t catlog_get_sys_time_str(char *buffer){
    uint32_t res = 0;

    return res;
}



CATLOG_WEAK_DECLARE void  catlog_open_stderr(void *p){} ;
CATLOG_WEAK_DECLARE void catlog_close_stderr(void *p){ fflush(stderr);} ;
CATLOG_WEAK_DECLARE void catlog_write_to_stderr(uint8_t * buffer,uint32_t size) {
    fwrite(buffer,1,size,stderr);
    fflush(stderr);
}

bsp_device_t *device = NULL;
CATLOG_WEAK_DECLARE void catlog_open_device(void *p){
    if(p){
        device = (bsp_device_t *)&p;
    }else{
        device = (bsp_device_t *)&CATLOG_OUTPUT_DEVICE;
    }
}
CATLOG_WEAK_DECLARE void catlog_close_device(void *p){
    device = NULL;
}
CATLOG_WEAK_DECLARE void catlog_write_to_device(uint8_t *buffer,uint32_t size){
    if(device){
        dev_write(device,buffer,size);
    }
}

#if CATLOG_OUTPUT_MODE == CATLOG_OUTPUT_TO_FILE
#include "fatfs.h"
static FIL *fp;
void catlog_open_file(void *p){
    char *filename = (char *)p;
    f_open(fp,filename,FA_WRITE | FA_CREATE_ALWAYS);
}
void catlog_close_file(void *p){
    f_close(fp);
}
void catlog_write_to_file(uint8_t * buffer,uint32_t size){
    UINT bw;
    f_write(fp,buffer,size,&bw);
}
#endif
#if CATLOG_MUTEX_LOCK_ENABLE == 1
void catlog_mutex_init(void *mutex){
    catlog_mutex_t m = mutex;
    *m = xSemaphoreCreateMutex();
}
void catlog_mutex_lock(void *mutex){
    xSemaphoreTake(*(catlog_mutex_t)mutex,portMAX_DELAY);
}
void catlog_mutex_unlock(void *mutex){
    xSemaphoreGive(*(catlog_mutex_t)mutex);
}
#endif
